
package cn.xabad.commons.io.input;

import java.io.IOException;
import java.io.InputStream;


public class BoundedInputStream extends InputStream {

    
    private final InputStream in;

    
    private final long max;

    
    private long pos = 0;

    
    private long mark = -1;

    
    private boolean propagateClose = true;

    
    public BoundedInputStream(InputStream in, long size) {
        
        
        this.max = size;
        this.in = in;
    }

    
    public BoundedInputStream(InputStream in) {
        this(in, -1);
    }

    
    @Override
    public int read() throws IOException {
        if (max >= 0 && pos >= max) {
            return -1;
        }
        int result = in.read();
        pos++;
        return result;
    }

    
    @Override
    public int read(byte[] b) throws IOException {
        return this.read(b, 0, b.length);
    }

    
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (max>=0 && pos>=max) {
            return -1;
        }
        long maxRead = max>=0 ? Math.min(len, max - pos) : len;
        int bytesRead = in.read(b, off, (int)maxRead);

        if (bytesRead==-1) {
            return -1;
        }

        pos+=bytesRead;
        return bytesRead;
    }

    
    @Override
    public long skip(long n) throws IOException {
        long toSkip = max>=0 ? Math.min(n, max - pos) : n;
        long skippedBytes = in.skip(toSkip);
        pos+=skippedBytes;
        return skippedBytes;
    }

    
    @Override
    public int available() throws IOException {
        if (max>=0 && pos>=max) {
            return 0;
        }
        return in.available();
    }

    
    @Override
    public String toString() {
        return in.toString();
    }

    
    @Override
    public void close() throws IOException {
        if (propagateClose) {
            in.close();
        }
    }

    
    @Override
    public synchronized void reset() throws IOException {
        in.reset();
        pos = mark;
    }

    
    @Override
    public synchronized void mark(int readlimit) {
        in.mark(readlimit);
        mark = pos;
    }

    
    @Override
    public boolean markSupported() {
        return in.markSupported();
    }

    
    public boolean isPropagateClose() {
        return propagateClose;
    }

    
    public void setPropagateClose(boolean propagateClose) {
        this.propagateClose = propagateClose;
    }
}
